<html>
<head><title>Calculator</title></head>
<body>

<h1>Calculator</h1>
(PHP by Jay Topiwala, HTML by Chu-Cheng Hsieh)<br />
Type an expression in the following box (e.g., 10.5+20*3/25).
<p>
<form method="GET">
<input type="text" name="expr"><input type="submit" value="Calculate">
</form>
</p>
<ul>
<li>Only numbers and +,-,* and / operators are allowed in the expression.
<li>The evaluation follows the standard operator precedence.
<li>The calculator does not support parentheses.
<li>The calculator handles invalid input "gracefully". It does not output PHP error messages.
</ul>
Here are some(but not limit to) reasonable test cases:
<ol>
  <li> A basic arithmetic operation:  3+4*5=23 </li>
  <li> An expression with floating point or negative sign : -3.2+2*4-1/3 = 4.46666666667, 3+-2.1*2 = -1.2 </li>
  <li> Some typos inside operation (e.g. alphabetic letter): Invalid input expression 2d4+1 </li>
</ol>
<br />
<?php
  $expr = $_GET["expr"];

// For catching divide by zero error (based on StackOverflow post from 18 Jun 2010)
// Behavior based on the example given -- not declared invalid, but no answer given
  function e($errno, $errstr, $errfile, $errline) {
  }
  
  set_error_handler('e');

// Expression defined as number (possibly negative and/or decimal), followed by 0 or more operator-then-number instances  
  if (preg_match("#^-?[0-9]+(\.[0-9]+)?([*/\-+]-?[0-9]+(\.[0-9]+)?)*$#", $expr, $pmresults)){
  // If no errors occur when evaluating, print expression equals answer, else print Invalid Expression
  if(eval("\$ans = $expr;") == NULL){
      echo "$expr = $ans";
	}
    else {
      echo "Invalid Expression: $expr";
    }
  }
// A blank expression is not invalid, according to the example
  elseif ($expr != ""){
    echo "Invalid Expression: $expr";
  }
?>
</body>
</html>